package com.sirui.jpa.web;

import com.sirui.jpa.model.JpaStudent;
import com.sirui.jpa.repository.StudentRepository;
import com.sirui.jpa.service.IStudentService;
import com.sirui.jpabox.JpaBox;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@Api(tags = "测试JPA持久化")
@RestController
@RequestMapping("/jpa")
public class SessionController {
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    IStudentService studentService;

    @GetMapping("test1")
    public String test1() {
        Specification<JpaStudent> specification = JpaBox.<JpaStudent>and().eq("age", 100).build();
        Optional<JpaStudent> optional = studentRepository.findOne(specification);
        JpaStudent jpaStudent = optional.get();
        jpaStudent.setName("wang");
        return jpaStudent.toString();
    }

    @GetMapping("test2")
    public String test2() {
        Specification<JpaStudent> specification = JpaBox.<JpaStudent>and().eq("age", 100).build();
        Optional<JpaStudent> optional = studentService.findOne(specification);
        JpaStudent jpaStudent = optional.get();
        return jpaStudent.toString();
    }

    @GetMapping("save")
    public String save() {
        JpaStudent student = JpaStudent.builder().name("李四").age(100).build();
        studentRepository.save(student);
        return student.toString();
    }
}
